package com.github.shiqiyue.blog.markdown.config;

import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.commons.io.IOUtils;
import org.redisson.client.codec.Codec;
import org.redisson.client.handler.State;
import org.redisson.client.protocol.Decoder;
import org.redisson.client.protocol.Encoder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufInputStream;

/***
 * fast json codec
 * 
 * @author wwy
 *
 */
public class FastJsonCodec implements Codec {
	private final static ParserConfig DEFAULT_REDIS_CONFIG = new ParserConfig();
	static {
		DEFAULT_REDIS_CONFIG.setAutoTypeSupport(true);
	}
	private final Decoder<Object> decoder = new Decoder<Object>() {
		@Override
		public Object decode(ByteBuf buf, State state) throws IOException {
			return JSON.parse(new String(IOUtils.toByteArray(new ByteBufInputStream(buf)), Charset.forName("UTF-8")),
					DEFAULT_REDIS_CONFIG);
		}
	};
	private final Encoder encoder = new Encoder() {
		@Override
		public ByteBuf encode(Object in) throws IOException {
			ByteBuf out = ByteBufAllocator.DEFAULT.buffer();
			out.writeBytes(JSON.toJSONBytes(in, SerializerFeature.WriteClassName));
			
			return out;
		}
	};
	
	@Override
	public Decoder<Object> getMapValueDecoder() {
		return decoder;
	}
	
	@Override
	public Encoder getMapValueEncoder() {
		return encoder;
	}
	
	@Override
	public Decoder<Object> getMapKeyDecoder() {
		return decoder;
	}
	
	@Override
	public Encoder getMapKeyEncoder() {
		return encoder;
	}
	
	@Override
	public Decoder<Object> getValueDecoder() {
		return decoder;
	}
	
	@Override
	public Encoder getValueEncoder() {
		return encoder;
	}
	
}
